<template>
  <div class="course-container">
    <nav-bar></nav-bar>
    <div class="course-content">
      <!-- 课程头部信息区域 -->
      <div class="course-header">
        <!-- 左侧课程图片 -->
        <div class="course-image">
          <img :src="courseImage" :alt="courseTitle">
        </div>
        
        <!-- 右侧课程标题和按钮 -->
        <div class="course-header-info">
          <h1 class="course-title">{{ courseTitle }}</h1>
          <button class="start-btn" @click="startLearning">开始学习</button>
        </div>
      </div>
      
      <!-- 课程详情区域 -->
      <div class="course-details">
        <!-- 课程简介 -->
        <div class="course-intro">
          <h2>课程简介</h2>
          <div class="instructor-info">
            <span class="label">讲师：</span>
            <span>{{ courseInstructor }}</span>
          </div>
          <p class="description">{{ courseDescription }}</p>
        </div>
        
        <!-- 课程大纲 -->
        <div class="course-outline">
          <h2>课程大纲</h2>
          <div class="chapters">
            <div class="chapter" v-for="(chapter, index) in chapters" :key="index">
              <div class="chapter-header" @click="toggleChapter(index)">
                <h3>{{ chapter.title }}</h3>
                <span class="toggle-icon">{{ chapter.isOpen ? '▼' : '▶' }}</span>
              </div>
              <div class="chapter-content" v-if="chapter.isOpen">
                <ul>
                  <li v-for="(lesson, lessonIndex) in chapter.lessons" :key="lessonIndex"
                    @click="updateLearningProgress(index, lessonIndex + 1)"
                    class="lesson-item">
                    {{ lesson.title }}
                    <span class="lesson-duration">{{ lesson.duration }}</span>
                  </li>
                </ul>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import NavBar from '@/components/NavBar.vue'
import axios from 'axios'

export default {
  name: 'CourseDetailView',
  components: {
    NavBar
  },
  data() {
    return {
      courseId: '',
      courseTitle: '',
      courseInstructor: '',
      courseDescription: '',
      courseImage: '',
      chapters: [
        {
          title: '第一章：线性表',
          lessons: [
            { title: '1.1 线性表的基本概念' },
            { title: '1.2 顺序表与链表' },
            { title: '1.3 线性表的应用' }
          ]
        },
        {
          title: '第二章：栈与队列',
          lessons: [
            { title: '2.1 栈的基本操作' },
            { title: '2.2 队列的基本操作' },
            { title: '2.3 栈与队列的应用' }
          ]
        },
        {
          title: '第三章：串',
          lessons: [
            { title: '3.1 串的基本操作' },
            { title: '3.2 串的模式匹配' },
            { title: '3.3 串的应用' }
          ]
        },
        {
          title: '第四章：树',
          lessons: [
            { title: '4.1 树的基本概念' },
            { title: '4.2 二叉树及其遍历' },
            { title: '4.3 树的应用' }
          ]
        },
        {
          title: '第五章：图',
          lessons: [
            { title: '5.1 图的基本概念' },
            { title: '5.2 图的遍历' },
            { title: '5.3 最短路径与最小生成树' }
          ]
        },
        {
          title: '第六章：查找',
          lessons: [
            { title: '6.1 顺序查找与折半查找' },
            { title: '6.2 平衡二叉查找树' },
            { title: '6.3 哈希查找' }
          ]
        },
        {
          title: '第七章：排序',
          lessons: [
            { title: '7.1 插入排序与交换排序' },
            { title: '7.2 选择排序与归并排序' },
            { title: '7.3 基数排序与外部排序' }
          ]
        }
      ]
    }
  },
  created() {
    // 从路由参数获取课程ID
    if (this.$route.query.id) {
      this.courseId = this.$route.query.id;
      this.fetchCourseData(this.courseId);
    }
  },
  methods: {
    toggleChapter(index) {
      this.chapters[index].isOpen = !this.chapters[index].isOpen;
    },
    
    updateLearningProgress(chapterIndex, lessonIndex) {
      // 从localStorage获取现有的学习课程列表
      let learningCourses = JSON.parse(localStorage.getItem('learningCourses')) || {};
      let inProgressCourses = learningCourses['正在进行'] || [];
      
      // 查找当前课程
      const courseIndex = inProgressCourses.findIndex(course => course.id === this.courseId);
      
      if (courseIndex !== -1) {
        // 更新课程进度
        inProgressCourses[courseIndex].lastChapter = chapterIndex;
        inProgressCourses[courseIndex].lastLesson = lessonIndex;
        inProgressCourses[courseIndex].buttonText = '继续';
        
        // 计算进度百分比
        let totalLessons = 0;
        let completedLessons = 0;
        
        this.chapters.forEach((chapter, cIndex) => {
          totalLessons += chapter.lessons.length;
          
          if (cIndex < chapterIndex) {
            completedLessons += chapter.lessons.length;
          } else if (cIndex === chapterIndex) {
            completedLessons += lessonIndex;
          }
        });
        
        // 更新进度
        inProgressCourses[courseIndex].progress = Math.round((completedLessons / totalLessons) * 100);
        
        // 更新localStorage
        learningCourses['正在进行'] = inProgressCourses;
        localStorage.setItem('learningCourses', JSON.stringify(learningCourses));
      }
    },
    async startLearning() {
      // 记录用户行为
      const userId = localStorage.getItem('userId'); // 假设已存储用户ID
      console.log('上报用户行为:', { userId, courseId: this.courseId });
      try {
        const res = await axios.post('/api/recommend/action', {
          userId: userId,
          courseId: this.courseId,
          actionType: 'learn'
        });
        console.log('recommend/action接口返回:', res.data);
      } catch (e) {
        console.warn('记录用户行为失败', e);
        if (e.response) {
          console.warn('接口返回内容:', e.response.data);
        }
      }
      // 将课程添加到用户的学习列表中
      const courseInfo = {
        id: this.courseId,
        title: this.courseTitle,
        school: this.courseInstructor.split('教授')[0] + '大学', // 模拟学校名称
        progress: 0,
        buttonText: '马上开始',
        lastChapter: 0,
        lastLesson: 0,
        chapters: this.chapters
      };
      
      // 从localStorage获取现有的学习课程列表
      let learningCourses = JSON.parse(localStorage.getItem('learningCourses')) || {};
      let inProgressCourses = learningCourses['正在进行'] || [];
      
      // 检查课程是否已经在列表中
      const existingCourseIndex = inProgressCourses.findIndex(course => course.id === courseInfo.id);
      
      if (existingCourseIndex === -1) {
        // 如果课程不在列表中，添加它
        inProgressCourses.push(courseInfo);
      } else {
        // 如果课程已经在列表中，更新它
        inProgressCourses[existingCourseIndex] = courseInfo;
      }
      
      // 更新localStorage
      learningCourses['正在进行'] = inProgressCourses;
      localStorage.setItem('learningCourses', JSON.stringify(learningCourses));
      
      // 跳转到课程学习问卷页面
      this.$router.push({ 
        path: '/course-survey', 
        query: { id: this.courseId } // 或 params: { id: this.courseId }
      });
    },
    async fetchCourseData(courseId) {
      try {
        const response = await axios.get(`/api/course/detail?id=${courseId}`);
        const data = response.data;
        this.courseTitle = data.title;
        this.courseInstructor = data.instructor;
        this.courseImage = data.image;
        this.courseDescription = data.description;
        // 章节展开逻辑：第一个章节默认展开
        this.chapters = (data.chapters || []).map((chapter, idx) => ({
          ...chapter,
          isOpen: idx === 0
        }));
      } catch (error) {
        console.error('获取课程详情失败:', error);
      }
    }
  }
}
</script>

<style scoped>
.course-container {
  width: 100%;
  background-color: #f8f9fa;
}

.course-content {
  width: 75%;
  margin: 0 auto;
  padding: 30px 0;
}

/* 课程头部样式 */
.course-header {
  display: flex;
  gap: 40px;
  margin-bottom: 40px;
  background-color: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.course-image {
  flex: 0 0 40%;
}

.course-image img {
  width: 100%;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.course-header-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.course-title {
  font-size: 32px;
  color: #1f2937;
  margin-bottom: 30px;
  line-height: 1.3;
}

.start-btn {
  padding: 12px 32px;
  background-color: #6d28d2;
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  align-self: flex-start;
}

.start-btn:hover {
  background-color: #5b21b6;
  transform: translateY(-2px);
}

/* 课程详情样式 */
.course-details {
  background-color: white;
  border-radius: 12px;
  padding: 30px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.course-intro, .course-outline {
  margin-bottom: 40px;
}

.course-intro h2, .course-outline h2 {
  font-size: 24px;
  color: #1f2937;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #e5e7eb;
}

.instructor-info {
  margin-bottom: 15px;
  font-size: 16px;
}

.label {
  color: #6b7280;
}

.description {
  color: #4b5563;
  line-height: 1.6;
  margin-bottom: 20px;
}

/* 章节样式 */
.chapters {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.chapter {
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  overflow: hidden;
}

.chapter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f8f9fa;
  cursor: pointer;
}

.chapter-header h3 {
  font-size: 18px;
  color: #1f2937;
  margin: 0;
}

.toggle-icon {
  color: #6d28d2;
  font-size: 14px;
}

.chapter-content {
  padding: 0 20px 15px;
}

.chapter-content ul {
  list-style: none;
  padding: 0;
  margin: 0;
}

.chapter-content li {
  padding: 12px 15px;
  border-bottom: 1px solid #f3f4f6;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: all 0.2s;
}

.chapter-content li:hover {
  background-color: #f8f7fa;
  color: #6d28d2;
}

.chapter-content li:last-child {
  border-bottom: none;
}

.lesson-duration {
  color: #6b7280;
  font-size: 14px;
}
</style>